package com.promote.algorithm;

/**
 * @ClassName IsValidBST
 * Description 验证二叉搜索树
 * @Author LiZiHao
 * Date 2022/4/10 17:50
 * @Version 1.0
 **/
public class IsValidBST {

    private class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public boolean isValidBST(TreeNode root) {

        return isValidBST(root,Long.MIN_VALUE,Long.MAX_VALUE);
    }



    public boolean isValidBST(TreeNode root, long minVal, long maxVal) {

        if (root == null) {
            return true;
        }

        //如果每个节点超出这个范围，就返回false
        if (root.val > maxVal || root.val < minVal) {
            return false;
        }

        return isValidBST(root.left, minVal, root.val) && isValidBST(root.right,root.val,maxVal);
    }
}
